<?php

class Bet_Model_NewsCategoryMapper extends Bet_Model_Mapper {

	public function __construct() {
		$this->setDbTableName("Bet_Model_DbTable_NewsCategory");
		$this->setId('news_category_id');
	}

	/**
	 * Retrieve an instance from the datastore by id
	 * @param $newsCatId
	 * @return Bet_Model_NewsCategory
	 */
	public function findById($newsCatId) {
		$data = $this->findByIdToArray($newsCatId);
		return ($data != null ? new Bet_Model_NewsCategory($data) : null);
	}

	/**
	 * Retrieve an instance's data from the datastore by id
	 * @param $newsCatId
	 * @return array Data fetched from the instance as an array
	 */
	public function findByIdToArray($newsCatId) {
		$result = $this->findToArray($newsCatId);
		return count($result) > 0 ? $result[0] : null;
	}

	/**
	 * Save or update an model object of a db instance
	 * @param Bet_Model_Group $group
	 * @return int | boolean Saving result - new row's id if save new object
	 * 		| TRUE if successed, otherwise FALSE if update an existing object
	 */
	public function save(Bet_Model_NewsCategory $newsCategory, $isUpdate = false) {
		$data = array(
			"title" => $newsCategory->getTitle(),
			"parent_id" => $newsCategory->getParentId(),
			"description" => $newsCategory->getDescription(),
		);

		if ($isUpdate) {
			$data["order"] = $newsCategory->getOrder();
			$data["status"] = $newsCategory->getStatus();
			$data["news_category_id"]  = $newsCategory->getNewsCategoryId();
		} else {
			$maxOrder = $this->_getMaxItemsOrder();
			$data["order"] = $maxOrder + 1;
			$data["news_category_id"]  = null;
			$data["status"] = Bet_Model_NewsCategory::STATUS_ENABLE;
		}

		return parent::save($data);
	}

	private function _getMaxItemsOrder() {
		$select = $this->getDbTable()->getAdapter()->select();
		$select->from('b24_news_category', new Zend_Db_Expr('max(`order`)'));
		return $this->getDbTable()->getAdapter()->query($select)->fetchColumn();
	}

}

